//index.js
var app = getApp();
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';

import {
  request
} from '../../utils/request';

import {
  indexApi
} from '../../api/preindex';

import {
  indexIcon,
  tabbarIcon
} from "../../mock/icon";

Page({
  /**
   * 页面的初始数据
   */
  data: {
    indexIcon,
    tabbarIcon,
    // 头部
    topAnimation: '',
    // 底部动画效果
    bottomAnimation: '',
    // 手机号授权
    getPhone: '',
       /**轮播图数据接口 */
   swiperImg:[
    {
      img:"https://wang-hh.oss-cn-beijing.aliyuncs.com/guHong/gu-banner1.png"
    },
    {
      img:"https://wang-hh.oss-cn-beijing.aliyuncs.com/guHong/gu-banner2.png"
    }
  ],
  maifangImg:[
    {
      img:'../../static/image/index/qkd.png',
      title:'取快递',
      busType:'1'
    },
    {
      img:'../../static/image/index/qwm.png',
      title:'取外卖',
      busType:'2'
    },
    {
      img:'../../static/image/index/qtg.png',
      title:'取团购',
      busType:'3'
    },
    {
      img:'../../static/image/index/bmbs.png',
      title:'帮买帮送',
      busType:'4'
    }
  ]
  },

  // 授权手机号
  async getPhoneNumber(e) {
    const that=this;
    // 取消手机号弹框
    this.setData({
      modalName: ''
    })
    // 微信数据存在就取消自定义授权弹框，防止，微信授权底部弹框和自定义授权弹框折叠
    if (e.detail.iv) {
      this.setData({
        getPhone: ''
      })
      wx.login({
        success: res => {
          let _code = res.code;
          //获取到code之后再发送给后端
          wx.request({
            url: indexApi.loginByWeixin(),
            data: {
              code: _code,
              iv: e.detail.iv,
              data: e.detail.encryptedData
            },
            method: 'POST',
            header: {
              'content-type': 'application/x-www-form-urlencoded' // 默认是json
            },
            success: function (res) {
              res = res.data;
              if (res.errno == 0) {
                console.log('login success');

                app.globalData.userInfo = res.data.userInfo;
                wx.setStorageSync('userInfo', JSON.stringify(res.data.userInfo));
                wx.setStorageSync('loginFlag', res.data.token);
                wx.setStorageSync('isClerk', res.data.isClerk);
                wx.setStorageSync('bindDept', res.data.bindDept);
                wx.setStorageSync('agreementState', res.data.agreementState);

                // callback();
                // 缓存手机号授权状态，以后登录不在触发授权弹框
                wx.setStorageSync('phoneAuthStatus', true);
                that.onShow();
              } else {
                console.log(".....fail.....");
              }
            },
            fail: function (res) {
              console.log(".....fail.....");
            }
          })
        }
      })
    } else {
      // 拒绝授权处理
      wx.showToast({
        icon: 'none',
        title: '已拒绝手机授权'
      })
    }
  },

  // 首页功能点击事件
  bindFunTap(e) {
    const dataset = e.currentTarget.dataset;
    wx.navigateTo({
      url: '/pages/' + dataset.url + '/' + dataset.url + '?busType=' +''
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  
    // 如果没有手机号授权状态就触发授权弹框
    const phoneAuthStatus = wx.getStorageSync('phoneAuthStatus');
    if (phoneAuthStatus == '') {
      this.setData({
        modalName: 'show',
        labFor: 'getPhone'
      })
    }
   

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: async function () {
    const phoneAuthStatus = wx.getStorageSync('phoneAuthStatus');

    if (phoneAuthStatus != '') {
    wx.login({
      success: res => {
        let _code = res.code;
        //获取到code之后再发送给后端
        wx.request({
          url: indexApi.refreshToken(),
          data: {
            code: _code
          },
          method: 'POST',
          header: {
            'content-type': 'application/x-www-form-urlencoded' // 默认是json
          },
          success: function (res) {
            res = res.data;
            if (res.errno == 0) {
              console.log('login success');
              
              app.globalData.userInfo = res.data.userInfo;
              wx.setStorageSync('loginFlag', res.data.token);
              wx.setStorageSync('agreementState', res.data.agreementState);
            } else {
              console.log(".....fail.....");
            }
          },
          fail: function (res) {
            console.log(".....fail.....");
          }
        })
      }
    })

    //绑定小区
    if(!wx.getStorageSync('bindDept')){
      Dialog.confirm({
        title: '',
        message: '请绑定您所在的小区',
      })
        .then(() => {
          wx.navigateTo({
            url: '/pages/bindDept/bindDept'
          })
        })
        .catch(() => {
          wx.navigateTo({
            url: '/pages/bindDept/bindDept'
          })
        });
    }
  }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.setData({
      topAnimation: '',
      bottomAnimation: ''
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.setData({
      topAnimation: '',
      bottomAnimation: ''
    })

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  
  gotoSelf:function(e){
    var num = e.currentTarget.dataset.index;
    var busType = e.currentTarget.dataset.bustype;
    var agreementState=wx.getStorageSync('agreementState')
		if(agreementState){
      if(num == 4){
        wx.navigateTo({
          url: '/pages/order/order'
        })
      } else {
        wx.navigateTo({
          url: '/pages/publish/publish?busType='+busType
        })
      }
		}else{
      wx.navigateTo({
        url: '/pages/agreement/agreement'
      })
    }
   
  },
})